package com.situ.gcbs.server;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.situ.gcbs.server.model.AdminUser;
import com.situ.gcbs.server.model.searchbean.AdminUserSearchBean;
import com.situ.gcbs.server.service.AdminUserService;
import com.situ.gcbs.server.util.Result;
import jakarta.servlet.http.HttpSession;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.UUID;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * @since 2024/5/24
 * <p>
 * created by 千堆雪 on 2024/5/24 16:02, last modified by 千堆雪 on 2024/5/24 16:02
 */
@RestController
@RequestMapping(value = "/api/v1/users", produces = "application/json")
public class UserApi {
    private AdminUserService adminUserService;

    @Value("jwt.secret.key")
    private String secretKey;

    @Autowired
    public void setAdminUserService(AdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    /**
     * 查询用户列表
     *
     * @param username 用户名
     * @return 用户列表
     */
    @GetMapping("/username")
    public Result findByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            throw new IllegalArgumentException("用户名不可为空");
        }
        AdminUser user = adminUserService.findByUsername(username);
        return Result.success(user);
    }

    /**
     * 认证登录
     *
     * @param adminUser 登录用户
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(AdminUser adminUser, HttpSession session) {
        if (!StringUtils.hasText(adminUser.getPhone())) {
            throw new IllegalArgumentException("用户名不可为空");
        }

        AdminUser user = adminUserService.findByUsername(adminUser.getPhone());

        //验证密码
        PasswordEncryptor pe = new StrongPasswordEncryptor();
        if (pe.checkPassword(user.getPassword(), adminUser.getPassword())) {//验证通过
            //颁发jwt
            String uuid = UUID.randomUUID().toString();
            String userKey = "admin_user_" + uuid;
            //此操作为模拟Redis存储用户信息
            session.setAttribute(userKey, adminUser);

            String jwt = JWT.create()
                    .withAudience(JSON.toJSONString(user))   //用户
                    .withIssuedAt(Instant.now())   //签发时间
                    .withExpiresAt(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant())    //过期时间
                    .sign(Algorithm.HMAC256(secretKey));  //使用hmac256进行签名

            return Result.success(Map.of("jwt", jwt));

        } else {
            return Result.failure("用户名或密码不正确");
        }
    }
}
